<template>
  <div class="chat-container">
    <!-- 左侧联系人列表 -->
    <div class="contact-list">
      <h2 class="list-title">联系人</h2>
      <div
          v-for="user in contactList"
          :key="user.userId"
          class="contact-item"
          :class="{ active: currentChat?.id === user.userId }"
          @click="selectChat(user)"
      >
        <div class="avatar">
          <image-preview :src="user.avatar"/>
        </div>
        <div class="info">
          <h3>{{ user.userName }}</h3>
        </div>
        <span v-if="user.unread" class="unread-badge">{{ user.unread }}</span>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <div class="chat-header">
        <h2>{{ currentChat?.userName || '选择联系人' }}</h2>
        <span class="status-dot" :class="{ online: currentChat?.online }"></span>
      </div>

      <!-- 消息展示区域 -->
      <div class="message-list" ref="messageContainer">
        <div
            v-for="message in sortedMessages"
            :key="message.tempId || message.messageId"
            :class="['message-item', message.senderId === currentUser.id ? 'sent' : 'received']"
        >
          <img
              class="message-avatar"
              :src="getAvatar(message.senderId)"
              alt="avatar"
          />
          <div class="message-content">
            <p>{{ message.content }}</p>
            <span class="time">
              {{ formatTime(message.sendTime) }}
              <span v-if="message.status === 'sending'" class="status-icon">🕒</span>
              <span v-if="message.status === 'failed'" class="status-icon">❌</span>
            </span>
          </div>
        </div>
      </div>

      <div v-if="appointmentStatus === '2'" class="consult-end-notice">
        <el-alert title="本次咨询已结束" type="info" center :closable="false"/>
      </div>
      <!-- 消息输入区域 -->
      <div class="input-area" v-if="currentChat">
        <input
            v-model="newMessage"
            @keyup.enter="sendChatMessage"
            placeholder="输入消息..."
            :disabled="appointmentStatus === '2'"
        />
        <button @click="sendChatMessage" v-if="appointmentStatus !== '2'">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {nextTick, onMounted, ref} from 'vue'
import {getCounselorChatList, getHistoryMsg} from "@/api/websocket/websocket.js";
import useUserStore from "@/store/modules/user.js";
import store from "@/store/index.js";
import dayjs from 'dayjs'
import {ElLoading} from "element-plus";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {useWebSocketStore} from '@/store/modules/websocket.js'
import {MessageType, SubType} from '@/constants/message'

const wsStore = useWebSocketStore()
// 消息列表
const messages = computed(() => {
  if (!currentChat.value) return [];
  const participants = [
    Number(currentUser.value.id),
    Number(currentChat.value.userId)
  ].sort((a, b) => a - b);
  console.log('participants:', participants)
  const chatId = participants.join('_');
  return wsStore.chatMessages.get(chatId) || [];
});

const messageContainer = ref(null)
// 输入框绑定
const newMessage = ref('')
// 联系人
const contactList = ref([])
// 当前聊天对象
const currentChat = ref(null)
// 上次点击联系人的id
const lastLoadedContactId = ref(null)
const appointmentStatus = ref('')

// 发送消息
const sendChatMessage = async () => {
  if (!newMessage.value.trim() || !currentChat.value) return;

  const messagePayload = {
    type: MessageType.CHAT_MSG,
    subType: SubType.CHAT.USER_TO_CONSULTANT,
    content: newMessage.value.trim(),
    receiverId: currentChat.value.userId,
  };

  // 清空输入前生成临时消息
  newMessage.value = '';

  // 通过 Store 发送
  await wsStore.sendMessage(messagePayload);
};

// 获取用户头像
const getAvatar = (id) => {
  // 优先从联系人列表获取
  const contact = contactList.value.find(user => user.userId === id)
  return contact?.avatar || currentUser.value.avatar
}

// 时间格式化
const formatTime = (timestamp) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}

// 当前用户
const currentUser = computed(() => {
  const userStore = useUserStore(store)
  return {
    ...userStore,
    id: Number(userStore.id) // 确保数值类型
  }
})

// 消息排序
const sortedMessages = computed(() => {
  return [...messages.value].sort((a, b) =>
      new Date(a.sendTime) - new Date(b.sendTime)
  );
});

watch(sortedMessages, () => {
  nextTick(scrollToBottom)
})

watch(appointmentStatus, (newVal) => {
  if (newVal === '2') {
    // 自动滚动到底部显示提示
    nextTick(scrollToBottom)
  }
})

// 选择聊天对象时
const selectChat = (user) => {
  console.log('当前选择用户ID:', user.userId, '类型:', typeof user.userId)
  if (lastLoadedContactId.value === user.userId) {
    return;
  }
  currentChat.value = user
  lastLoadedContactId.value = user.id;
  nextTick(() => {
    document.querySelector('.input-area input')?.focus()
  })
  // 清空旧消息
  messages.value = []
  // 加载历史消息
  loadHistoryMsg();
}

// 加载历史消息
async function loadHistoryMsg() {
  if (!currentChat.value) return;

  const loading = ElLoading.service({target: '.message-list'});
  try {
    const params = {
      pageNum: 1,
      pageSize: 1000,
      sortOrder: 'desc'
    };

    const res = await getHistoryMsg(
        currentUser.value.id,
        currentChat.value.userId,
        params
    );

    // 增加时间格式标准化
    const normalizeTime = (timeStr) => {
      return new Date(timeStr).toISOString();
    };

    const formattedMessages = res.rows.map(msg => ({
      ...msg,
      // 增加临时ID关联字段
      _clientTempId: msg.tempId ? msg.tempId.replace('client_', '') : null,
      sendTime: normalizeTime(msg.sendTime),
      isHistory: true,
      status: 'success'
    }));

    // 合并前处理重复
    const participants = [
      Number(currentUser.value.id),
      Number(currentChat.value.userId)
    ].sort((a, b) => a - b)
    const chatId = participants.join('_');

    // 获取当前消息列表
    const currentMessages = wsStore.chatMessages.get(chatId) || [];

    // 创建映射：客户端临时ID -> 服务端消息
    const serverMsgMap = new Map();
    formattedMessages.forEach(msg => {
      if (msg._clientTempId) {
        serverMsgMap.set(msg._clientTempId, msg);
      }
    });

    const filteredCurrent = currentMessages.filter(currentMsg => {
      // 保留所有未完成消息
      if (currentMsg.status !== 'success') return true;

      // 实时消息不参与历史去重
      return !currentMsg.isHistory;
    });

    // 执行合并
    wsStore.mergeHistoryMessages(chatId, [...filteredCurrent, ...formattedMessages]);

    // 强制触发响应式更新
    wsStore.chatMessages = new Map(wsStore.chatMessages);

  } catch (error) {
    console.error('加载历史消息失败:', error);
  } finally {
    loading.close();
    await nextTick(scrollToBottom);
  }
}

// 滚动方法
const scrollToBottom = () => {
  if (messageContainer.value) {
    nextTick(() => {
      messageContainer.value.scrollTo({
        top: messageContainer.value.scrollHeight,
        behavior: 'smooth'
      })
    })
  }
}


// todo 获取咨询师列表  getAllChatList
function initChatList() {
  getCounselorChatList().then(response => {
    contactList.value = response.rows.map(user => ({
      ...user,
      userId: Number(user.userId)
    }))
  })
}

// 获取所有联系人
/*function initChatList() {
  getAllChatList().then(response => {
    contactList.value = response.rows;
  })
}*/

watch(
    () => wsStore.chatMessages,
    () => {
      nextTick(scrollToBottom);
    },
    {deep: true}
);


// 组件挂载时添加监听
onMounted(() => {
  initChatList();
});
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 80vh;
  overflow: hidden;
}

/* 联系人列表样式 */
.contact-list {
  width: 320px;
  border-right: 2px solid #e0e0e0;
  box-shadow: 4px 0 6px -4px rgba(0, 0, 0, 0.1);
}

.list-title {
  padding: 16px;
  margin: 0;
  font-size: 18px;
  color: #333;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  transition: background 0.3s;
}

.contact-item:hover {
  background: #f5f5f5;
}

.contact-item.active {
  background: #e3f2fd;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2196f3;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.info h3 {
  margin: 0;
  font-size: 16px;
}

.last-msg {
  margin: 4px 0 0;
  color: #666;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.unread-badge {
  background: #ff4081;
  color: white;
  border-radius: 12px;
  padding: 2px 8px;
  font-size: 12px;
  margin-left: auto;
}

/* 聊天区域样式 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
  margin-left: 8px;
}

.status-dot.online {
  background: #4caf50;
}

/* 消息列表样式 */
.message-list {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  min-height: 0;
}

.message-item {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-start;
}

/* 接收消息样式 */
.message-item.received {
  justify-content: flex-start;
}

.message-item.received .message-avatar {
  order: 1;
  margin-right: 15px;
}

.message-item.received .message-content {
  order: 2;
  background: #f5f5f5;
  margin-left: 8px;
}

/* 发送消息样式 */
.message-item.sent {
  justify-content: flex-end;
}

.message-item.sent .message-avatar {
  order: 2;
  margin-left: 15px;
}

.message-item.sent .message-content {
  order: 1;
  background: #4ecb73;
  margin-right: 8px;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.message-content {
  max-width: 75%;
  padding: 12px 16px;
  border-radius: 15px;
  position: relative;
}

.time {
  font-size: 12px;
  color: #666;
  margin-top: 6px;
  display: block;
  text-align: right;
}

/* 输入区域样式 */
.input-area {
  position: sticky;
  display: flex;
  padding: 20px;
  border-top: 1px solid #eee;
  height: 60px;
  align-items: center;
  margin-top: auto;
  box-sizing: border-box;
}

.input-area input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  margin-right: 8px;
  height: 40px;
  transition: all 0.3s;
  font-size: 14px;
}

.input-area input:focus {
  border-color: #2196f3;
  box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
}

.input-area button {
  padding: 10px 20px;
  height: 40px;
  background: #2196f3;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

.input-area button:hover {
  background: #1976d2;
}
</style>
